package org.jiucheng.magpiebridge.manager.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.magpiebridge.manager.dto.OAuth2GithubControlDto;
import org.jiucheng.magpiebridge.manager.dto.SysUserDto;
import org.jiucheng.magpiebridge.manager.entity.Client;
import org.jiucheng.magpiebridge.manager.entity.ClientMapping;
import org.jiucheng.magpiebridge.manager.entity.Server;
import org.jiucheng.magpiebridge.manager.entity.SysUser;
import org.jiucheng.magpiebridge.manager.entity.SysUserServer;
import org.jiucheng.magpiebridge.manager.handler.UserCheckHandler;
import org.jiucheng.magpiebridge.manager.out.TplOut;
import org.jiucheng.magpiebridge.manager.service.IClientService;
import org.jiucheng.magpiebridge.manager.service.IOAuth2ControlService;
import org.jiucheng.magpiebridge.manager.service.ISysUserService;
import org.jiucheng.magpiebridge.manager.util.ThreadArgs;
import org.jiucheng.plugin.db.IBaseService;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.Param;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.RequestMethod;
import org.jiucheng.web.util.WebUtil;

/**
 * 
 * @author jiucheng
 *
 */
@Controller(UserCheckHandler.class)
public class IndexController {
    
    @Inject
    private IBaseService baseService;
    @Inject
    private IClientService clientService;
    @Inject
    private ISysUserService sysUserService;
    @Inject("OAuth2ControlService")
    private IOAuth2ControlService OAuth2ControlService;
    
    @RequestMapping(value = "/clients_mappings_edit", method = RequestMethod.GET, out = TplOut.class)
    public String clientsMappingsEdit(@Param("id") Long id, HttpServletRequest req, HttpServletResponse res) throws IOException {
        req.setAttribute("uri", "clients");
        req.setAttribute("header-title", "隧道管理/映射/编辑");
        if (id == null) {
            res.sendError(404);
            return null;
        }
        ClientMapping clientMapping = baseService.get(ClientMapping.class, id);
        if (clientMapping == null) {
            res.sendError(404);
            return null;
        }
        Client client = baseService.get(Client.class, clientMapping.getClientId());
        if (client == null || !client.getUserId().equals(ThreadArgs.getGid())) {
            res.sendError(404);
            return null;
        }
        Server server = baseService.get(Server.class, clientMapping.getServerId());
        if (server == null) {
            res.sendError(404);
            return null;
        }
        req.setAttribute("clientMapping", clientMapping);
        req.setAttribute("client", client);
        req.setAttribute("server", server);
        return "clients_mappings_edit";
    }
    
    @RequestMapping(value = "/clients_mappings_add", method = RequestMethod.GET, out = TplOut.class)
    public String clientsMappingsAdd(@Param("clientId") Long clientId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        if (clientId == null) {
            res.sendError(404);
            return null;
        }
        Client client = baseService.get(Client.class, clientId);
        if (client == null || !client.getUserId().equals(ThreadArgs.getGid())) {
            res.sendError(404);
            return null;
        }
        Integer protocolType = 0;
        Server server = baseService.get(Server.class, client.getServerId());
        if (server != null)
        	protocolType = server.getProtocolType();
        req.setAttribute("protocolType", protocolType);
        req.setAttribute("client", client);
        req.setAttribute("uri", "clients");
        req.setAttribute("header-title", "隧道管理/映射/新增");
        List<Server> servers = baseService.list(new Server());
        req.setAttribute("servers", servers);
        return "clients_mappings_add";
    }
    
    @RequestMapping(value = "/clients_mappings", method = RequestMethod.GET, out = TplOut.class)
    public String clientsMappings(@Param("clientId") Long clientId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        if (clientId == null) {
            res.sendError(404);
            return null;
        }
        Client client = baseService.get(Client.class, clientId);
        if (client == null || !client.getUserId().equals(ThreadArgs.getGid())) {
            res.sendError(404);
            return null;
        }
        Server server = baseService.get(Server.class, client.getServerId());
        if (server == null) {
            res.sendError(404);
            return null;
        }
        req.setAttribute("client", client);
        req.setAttribute("server", server);
        req.setAttribute("uri", "clients");
        req.setAttribute("header-title", "隧道管理/映射");
        ClientMapping clientMapping = new ClientMapping();
        clientMapping.setClientId(client.getId());
        List<ClientMapping> clientMappings = baseService.list(clientMapping);
        req.setAttribute("clientMappings", clientMappings);
        return "clients_mappings";
    }
    
    @RequestMapping(value = "/clients_edit", method = RequestMethod.GET, out = TplOut.class)
    public String clientsEdit(@Param("id") Long id, HttpServletRequest req, HttpServletResponse res) throws IOException {
        if (id == null) {
            res.sendError(404);
            return null;
        }
        req.setAttribute("uri", "clients");
        req.setAttribute("header-title", "隧道管理/编辑");
        Client client = baseService.get(Client.class, id);
        if (client == null || !client.getUserId().equals(ThreadArgs.getGid())) {
            res.sendError(404);
            return null;
        }
        Server server = baseService.get(Server.class, client.getServerId());
        req.setAttribute("client", client);
        req.setAttribute("server", server);
        return "clients_edit";
    }
    
    @RequestMapping(value = "/clients_add", method = RequestMethod.GET, out = TplOut.class)
    public String clientsAdd(HttpServletRequest request) {
        request.setAttribute("uri", "clients");
        request.setAttribute("header-title", "隧道管理/新增");
        List<Server> servers = baseService.list(new Server());
        request.setAttribute("servers", servers);
        return "clients_add";
    }
    
    @RequestMapping(value = "/clients", method = RequestMethod.GET, out = TplOut.class)
    public String clients(HttpServletRequest request) {
        request.setAttribute("uri", "clients");
        request.setAttribute("header-title", "隧道管理");
        request.setAttribute("clients", clientService.listClientDto(ThreadArgs.getGid())); 
        return "clients";
    }
    
    @RequestMapping(value = "/users_edit", method = RequestMethod.GET, out = TplOut.class)
    public String usersEdit(@Param("id") Long id, HttpServletRequest req, HttpServletResponse res) throws IOException {
    	req.setAttribute("uri", "users");
    	req.setAttribute("header-title", "用户管理/编辑");
        if (id == null) {
            res.sendError(404);
            return null;
        }
        SysUser sysUser = baseService.get(SysUser.class, id);
        if (sysUser == null) {
            res.sendError(404);
            return null;
        }
        req.setAttribute("isSuper", ThreadArgs.getIsSuper());
        SysUserDto sysUserDto = new SysUserDto();
        sysUserDto.setId(sysUser.getId());
        sysUserDto.setEmail(sysUser.getEmail());
        sysUserDto.setInactive(sysUser.getInactive());
        sysUserDto.setIsSuper(sysUser.getIsSuper());
        
        SysUserServer sysUserServer = sysUserService.getSysUserServer(sysUser.getId(), 0L);
        if (sysUserServer != null) {
        	sysUserDto.setPortCountLimit(sysUserServer.getPortCountLimit());
        	sysUserDto.setSubCountLimit(sysUserServer.getSubCountLimit());
        } else {
        	sysUserDto.setPortCountLimit(-1L);
        	sysUserDto.setSubCountLimit(-1L);
        }
        req.setAttribute("sysUser", sysUserDto);
        return "users_edit";
    }
    
    @RequestMapping(value = "/users_add", method = RequestMethod.GET, out = TplOut.class)
    public String usersAdd(HttpServletRequest request) {
        request.setAttribute("uri", "users");
        request.setAttribute("header-title", "用户管理/新增");
        return "users_add";
    }
    
    @RequestMapping(value = "/users", method = RequestMethod.GET, out = TplOut.class)
    public String users(
    		@Param("currentPage") Integer currentPage,
    		@Param("keyword") String keyword,
    		HttpServletRequest request) {
    	if (currentPage == null || currentPage < 1) {
    		currentPage = 1;
    	}
        request.setAttribute("uri", "users");
        request.setAttribute("header-title", "用户管理");
        request.setAttribute("page", sysUserService.page(currentPage, keyword)); 
        return "users";
    }
    
    @RequestMapping(value = "/servers_edit", method = RequestMethod.GET, out = TplOut.class)
    public String serversEdit(@Param("id") Long id, HttpServletRequest req, HttpServletResponse res) throws IOException {
        req.setAttribute("uri", "servers");
        req.setAttribute("header-title", "服务器组/编辑");
        if (id == null) {
            res.sendError(404);
            return null;
        }
        Server server = baseService.get(Server.class, id);
        if (server == null) {
            res.sendError(404);
            return null;
        }
        req.setAttribute("isSuper", ThreadArgs.getIsSuper());
        req.setAttribute("server", server);
        return "servers_edit";
    }
    
    @RequestMapping(value = "/servers_add", method = RequestMethod.GET, out = TplOut.class)
    public String serversAdd(HttpServletRequest request) {
        request.setAttribute("uri", "servers");
        request.setAttribute("header-title", "服务器组/新增");
        return "servers_add";
    }
    
    @RequestMapping(value = "/servers", method = RequestMethod.GET, out = TplOut.class)
    public String servers(HttpServletRequest request) {
        request.setAttribute("uri", "servers");
        request.setAttribute("header-title", "服务器组");
        request.setAttribute("isSuper", ThreadArgs.getIsSuper());
        List<Server> servers = baseService.list(new Server());
        request.setAttribute("servers", servers);
        return "servers";
    }
    
    @RequestMapping(value = "/index", method = RequestMethod.GET, out = TplOut.class)
    public String index(HttpServletRequest request) {
        request.setAttribute("uri", "index");
        request.setAttribute("header-title", "工作台");
        return "index";
    }
    
    @RequestMapping(value = "/editpwd", method = RequestMethod.GET, out = TplOut.class)
    public String editpwd(HttpServletRequest request) {
        request.setAttribute("uri", "index");
        request.setAttribute("header-title", "修改密码");
        boolean noPwd = false;
        SysUser sysUser = baseService.get(SysUser.class, ThreadArgs.getGid());
        if (sysUser != null && StringUtil.isBlank(sysUser.getPassword())) {
        	noPwd = true;
        }
        request.setAttribute("noPwd", noPwd);
        return "editpwd";
    }
    
    @RequestMapping(value = "/settings", method = RequestMethod.GET, out = TplOut.class)
    public String settings(HttpServletRequest request) {
        request.setAttribute("uri", "settings");
        request.setAttribute("header-title", "基础设置");
    	OAuth2GithubControlDto githubControl = OAuth2ControlService.getOauth2GithubControlDto();
    	if (githubControl == null) {
    		githubControl = new OAuth2GithubControlDto();
    		githubControl.setCallback("");
    		githubControl.setClientId("");
    		githubControl.setClientSecret("");
    		githubControl.setOpened("F");
    	}
    	request.setAttribute("githubControl", githubControl);
        return "settings";
    }
    
    @RequestMapping(value = "/", method = RequestMethod.GET, out = TplOut.class)
    public void main() {
        WebUtil.redirect("/index?utm_source=/");
    }
}
